import api from '@/store/api';
import { ReturnGetters, ActionContext } from '@/types/store';

const state = {};
type State = typeof state;

const getters = {};
type Getters = ReturnGetters<typeof getters>;

const mutations = {};

type Multations = keyof typeof mutations;

const actionsNames = ['download'] as const;
type ActionNames = typeof actionsNames[number];

const actions = {
  async download(
    { dispatch }: ActionContext<ActionNames, Multations, State, Getters>,
    { dataType, fileName }: any
  ) {
    let params = {
      DiagnosticDataType: 'OEM',
      OEMDiagnosticDataType: dataType,
    };
    return await api
      .post(
        '/redfish/v1/Systems/system/LogServices/HostLogger/Actions/LogService.CollectDiagnosticData',
        params
      )
      .then((response) => {
        let disposition = response.headers['content-disposition'];
        let regex = /filename="(.*?)"/;
        let match = disposition.match(regex);
        let downloadName = match ? match[1] : `${fileName}.tar`;
        let url = window.URL.createObjectURL(new Blob([response.data]));
        let link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', downloadName);
        document.body.appendChild(link);
        link.click();
        link.parentNode?.removeChild(link);
        return 'Success';
      })
      .catch(() => {
        throw new Error('Failed');
      });
  },
};

const SystemLogsStore = {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
};

export default SystemLogsStore;
